package by.grsu.pereverzev.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import by.grsu.pereverzev.entity.Application;
import by.grsu.pereverzev.table.ApplicationTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class ApplicationDao extends AbstractDao<ApplicationTable, Application> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3089970014408945860L;

	public ApplicationDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	public List<Application> getByPassengerId(Long id) {
		List<Application> result = new ArrayList<Application>();
		List<Application> all = getAll();
		for (Application ap : all) {
			if (ap.getPassengerId().equals(id)) {
				result.add(ap);
			}
		}
		return result;
	}
	
	@Override
	public Long saveNew(final Application newApplication) {
		// set ID
		Long nextId = getNextId();
		newApplication.setId(nextId);
		// get existing data
		final ApplicationTable applicationTable = deserializeFromXml();
		// add new row
		applicationTable.getRows().add(newApplication);
		// save data
		serializeToXml(applicationTable);
		return nextId;
	}

	@Override
	public void update(final Application entity) {
		// get existing data
		final ApplicationTable applicationTable = deserializeFromXml();
		// find by ID
		for (final Application row : applicationTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				// found!!!
				// copy data
				row.setBillId(entity.getBillId());
				row.setId(entity.getId());
				row.setPassengerId(entity.getPassengerId());
				row.setFlightId(entity.getFlightId());
				break;
			}
		}
		// save updated table
		serializeToXml(applicationTable);
	}

	@Override
	public Application get(final Serializable id) {
		// get existing data
		final ApplicationTable applicationTable = deserializeFromXml();
		// find by ID
		for (final Application row : applicationTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}
	
	@Override
	public List<Application> getAll() {
		// get existing data
		final ApplicationTable applicationTable = deserializeFromXml();
		return applicationTable.getRows();
	}
	
	@Override
	public void delete(final Serializable id) {
		// get existing data
		final ApplicationTable applicationTable = deserializeFromXml();
		// find by ID
		Application toBeDeleted = null;
		for (final Application row : applicationTable.getRows()) {
			if (row.getId().equals(id)) {
				// found!!!
				toBeDeleted = row;
				break;
			}
		}
		// remove from list
		applicationTable.getRows().remove(toBeDeleted);
		// save updated table
		serializeToXml(applicationTable);
	}

	@Override
	protected Class<ApplicationTable> getTableClass() {
		return ApplicationTable.class;
	}



}
